package com.zy.algorithm.v2.sort;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.zy.activity.BaseFragment;
import com.zy.algorithm.v2.R;
import com.zy.algorithm.v2.bean.SimpleNode;
import com.zy.view.HeapView;

import java.util.List;

public abstract class BaseHeapSortFragmentV1 extends BaseFragment {
    @Override
    protected int getLayout() {
        return R.layout.heap_sort_layout_v1;
    }

    protected HeapView heapView;
    TextView title;
    TextView des;
    List<? extends SimpleNode> list;
    int curIndex = 0;
    protected int endingIndex = 0;
    protected int endingSize = 0;
    protected int[] ends;

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            play(list.get(curIndex));
            curIndex++;
            Log.d("BaseHeapSortFragmentV2", "curIndex:" + curIndex);
            if (curIndex < list.size()) {
                mHandler.postDelayed(runnable, 50);
            } else {
                //mHandler.postDelayed(ending, 16);
            }
        }
    };

//    Runnable ending = new Runnable() {
//        @Override
//        public void run() {
//            getEndLineSetView().ending(ends, di(), emptyDi(), endingIndex);
//            endingIndex = endingIndex + 2;
//            if (endingIndex < endingSize) {
//                mHandler.postDelayed(ending, 16);
//            } else {
//                getEndLineSetView().ending(ends, di(), emptyDi(), endingSize);
//            }
//        }
//    };


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        heapView = view.findViewById(R.id.base_sort_layout_v1_heap_view);
        title = view.findViewById(R.id.base_sort_layout_v2_title);
        des = view.findViewById(R.id.base_sort_layout_v2_des);
        des.setText("");
        list = getDataList();

        ends = getEnds(list.get(list.size() - 1));
        endingSize = ends.length;

        mHandler.postDelayed(runnable, 500);


        title.setText(getTitle());
        init(list.get(0));
    }

    private void init(SimpleNode simpleNode) {
        heapView.setData(simpleNode.getStepEnd(), simpleNode.getOpIndex());
    }

    protected int[] getEnds(SimpleNode simpleNode) {
        return simpleNode.getStepEnd();
    }

    protected HeapView getEndLineSetView() {
        return heapView;
    }


    protected void play(SimpleNode curNode) {
        des.setText(curNode.getDes());
        heapView.setData(curNode.getStepEnd(), curNode.getOpIndex());
    }

    protected abstract String getTitle();

    abstract List<? extends SimpleNode> getDataList();

}
